function [b,fileStations] = readStationList(filenaxls)
%readStationList - Read station list from an Excel or an ASCII file
%
%   [listStations,fileStations] = readStationList(fileStations)
%
% This function takes the GNSS stations listed in the Excel or ASCII file 
% fileStations. Each station must be represented by its 4-character name. 
% In the case of an Excel file, the station names must be placed in the
% first column (no more than the first column is read by this function).
% In the case of an ASCII file, only a column is admitted. 
% If fileStations is undefined or empty, the filename can be managed
% in interactive way.
% The output stationList is the NB-by-1 cell array whose elements are the 
% station names (clearly, NB is the number of taken stations).
% If one or more rows are empty, they are deleted, i.e. statioList has 
% non-empty rows only.
% If the file load is successful, the name of effectively loaded file
% is also returned.
% If the file load is unsuccesful, a warning message is shown and B = []
% is returned.

% G. Teza, 2022

if (nargin < 1) || isempty(filenaxls)
    [fily1,pathy1] = uigetfile(...
        {'*.xlsx','(*.xlsx)';'*.xls','(*.xls)';'*.txt','(*.txt)'},...
        'STATION LIST FILE (*.xls/*.xlsx/*.txt)');
    if isnumeric(fily1) || isnumeric(pathy1)
        filena1 = []; 
    else
        filena1 = fullfile(pathy1,fily1);
    end
else
    filena1 = filenaxls;
end 

IDval = false;
if ~isempty(filena1)
    [~,~,ext1] = fileparts(filena1);
    if strcmpi(ext1,'.xlsx') || strcmpi(ext1,'.xls')
        [~,b] = xlsread(filena1); %#ok<XLSRD> 
        if (size(b,1)) > 1 && (numel(b{1,:}) > 4)
            b = b(2:end,1); % header removal, if necessary
        end
    elseif strcmpi(ext1,'.txt')
        fid = fopen(filena1);
        if fid ~= -1
            b1 = textscan(fid,'%s');
            b1b = b1{:};
            b2 = char(b1{:});
            [nrow,nchar] = size(b2);
            if (nrow > 1) && ((numel(b2(1,:)) > 4) || strcmp(b2(2,nchar),' '))  
                % in this case, the first row is the header
                b = b1b(2:end,:);
            else
                b = b1b;
            end
        else
            b = [];
        end
    end
    if ~isempty(b)
        nr = size(b,1);
        Ie = false(nr,1);
        for k = 1:nr
            Ie(k) = isempty(b{k});
        end
        b(Ie) = [];
        if ~isempty(b)
            IDval = true;
        end
    end
end
fileStations = filena1;

if ~IDval
    warning('No station names');
    fileStations = [];
    b = [];
end